/**
 * jmpopups
 * Copyright (c) 2009 Otavio Avila (http://otavioavila.com)
 * Licensed under GNU Lesser General Public License
 *
 * @docs http://jmpopups.googlecode.com/
 * @version 0.5.1
 *
 */
(function($) {
    var openedPopups = [];
    var popupLayerScreenLocker = false;
    var focusableElement = [];
    var setupJqueryMPopups = {
        screenLockerBackground: "#a1a1a1",
        screenLockerOpacity: "0.5"
    };
    var locales = {
        ZH_CN: {
            close: '关闭',
            confirm: '确定',
            cancel: '取消',
            titleInfo: '系统提示'
        },
        ZH_TW: {
            close: '關閉',
            confirm: '確定',
            cancel: '取消',
            titleInfo: '系統提示'
        },
        EN_US: {
            close: 'close',
            confirm: 'Yes',
            cancel: 'No',
            titleInfo: 'System prompts'
        }
    }
    
    var confirmHtml = '<div id="popWin">' +
    '  <h2><span class="pocClo" onclick="$.closePopupLayer(\'sysConfirmPop\')">&nbsp;</span>TITLEINFO</h2>' +
    '  <div class="popBox">' +
    '    <div class="popCon">' +
    '      <div>' +
    '        <p class="STYLEINFO">TEXTINFO</p>' +
    '      </div>' +
    '      <div class="clr"></div>' +
    '    </div>' +
    '  <div class="bts c">' +
    '    <a id="confirmYes" href="javascript:void(0)" title="Yes" ><span>YESTAG</span></a>' +
    '    <a id="confirmNo" href="javascript:void(0)"  title="No" ><span>NOTAG</span></a>' +
    '  </div>' +
    '</div>';
    
    var alertHtml = '<div id="popWin">' +
    '  <h2><span class="pocClo" onclick="$.closePopupLayer(\'sysAlertPop\')">&nbsp;</span>TITLEINFO</h2>' +
    '  <div class="popBox">' +
    '    <div class="popCon">' +
    '      <div>' +
    '        <p class="STYLEINFO">TEXTINFO</p>' +
    '      </div>' +
    '      <div class="clr"></div>' +
    '    </div>' +
    '  <div class="bts c">' +
    '    <a id="alertYes" href="javascript:void(0)" title="Yes" ><span>YESTAG</span></a>' +
    '  </div>' +
    '</div>';
    
    /*
     var confirmHtml = '<div class="popTable popWb">' +
     '<div class="title" >' +
     '<div class="fl">TITLEINFO</div>' +
     '<a href="javascript:void(0)" onclick="$.closePopupLayer(\'sysConfirmPop\')">CLOSETAG</a>' +
     '</div>' +
     '<div class="popTableCont topBox">' +
     '<span class="inf"></span>' +
     '<p class="fl">TEXTINFO</p>' +
     '</div>' +
     '<div class="btnBox">' +
     '<a id="confirmYes" href="javascript:void(0)" title="Yes" >YESTAG</a>' +
     '<a id="confirmNo" href="javascript:void(0)"  title="No" >NOTAG</a>' +
     '</div>' +
     '</div>';
     var alertHtml = '<div class="popTable popWb">' +
     '<div class="title" >' +
     '<div class="fl">TITLEINFO</div>' +
     '<a href="javascript:void(0)" onclick="$.closePopupLayer(\'sysAlertPop\')">CLOSETAG</a>' +
     '</div>' +
     '<div class="popTableCont topBox">' +
     '<span class="inf"></span>' +
     '<p class="fl">TEXTINFO</p>' +
     '</div>' +
     '<div class="btnBox">' +
     '<a id="alertYes" href="javascript:void(0)" title="Yes" >YESTAG</a>' +
     '</div>' +
     '</div>';
     */
    $.setupJMPopups = function(settings) {
        setupJqueryMPopups = jQuery.extend(setupJqueryMPopups, settings);
        return this;
    }
    
    $.openPopupLayer = function(settings) {
        if (typeof(settings.name) != "undefined" && !checkIfItExists(settings.name)) {
            settings = jQuery.extend({
                width: "auto",
                height: "auto",
                parameters: {},
                target: "",
                content: "",
                success: function() {
                },
                error: function() {
                },
                beforeClose: function() {
                },
                afterClose: function() {
                },
                reloadSuccess: null,
                cache: false,
                enableScreenLockClick: false
            }, settings);
            loadPopupLayerContent(settings, true);
            return this;
        }
    }
    
    $.openPopupAlertLayer = function(settings) {
        settings = jQuery.extend({
            width: "auto",
            height: "auto",
            parameters: {},
            name: "sysAlertPop",
            target: "sysAlert",
            titleInfo: getJmpopupsLocalInfo("titleInfo"),
            textInfo: "",
            success: function() {
            },
            error: function() {
            },
            beforeClose: function() {
            },
            afterClose: function() {
            },
            yesClick: function() {
            },
            reloadSuccess: null,
            cache: false,
            enableAutoClose: true,
            enableScreenLockClick: false
        }, settings);
        loadPopupLayerContent(settings, true);
        return this;
    }
    
    $.openPopupConfirmLayer = function(settings) {
        settings = jQuery.extend({
            width: "auto",
            height: "auto",
            parameters: {},
            name: "sysConfirmPop",
            target: "sysConfirm",
            titleInfo: getJmpopupsLocalInfo("titleInfo"),
            textInfo: "",
            success: function() {
            },
            error: function() {
            },
            beforeClose: function() {
            },
            afterClose: function() {
            },
            noClick: function() {
            },
            reloadSuccess: null,
            cache: false,
            enableAutoClose: true,
            enableScreenLockClick: false
        }, settings);
        loadPopupLayerContent(settings, true);
        return this;
    }
    
    $.closePopupLayer = function(name) {
        if (name) {
            for (var i = 0; i < openedPopups.length; i++) {
                if (openedPopups[i].name == name) {
                    var thisPopup = openedPopups[i];
                    
                    openedPopups.splice(i, 1)
                    
                    thisPopup.beforeClose();
                    
                    $("#popupLayer_" + name).fadeOut(-1, function() {
                        $("#popupLayer_" + name).remove();
                        
                        focusableElement.pop();
                        
                        if (focusableElement.length > 0) {
                            $(focusableElement[focusableElement.length - 1]).focus();
                        }
                        
                        thisPopup.afterClose();
                        hideScreenLocker(name);
                    });
                    
                    break;
                }
            }
        }
        else {
            if (openedPopups.length > 0) {
                $.closePopupLayer(openedPopups[openedPopups.length - 1].name);
            }
        }
        
        return this;
    }
    
    $.reloadPopupLayer = function(name, callback) {
        if (name) {
            for (var i = 0; i < openedPopups.length; i++) {
                if (openedPopups[i].name == name) {
                    if (callback) {
                        openedPopups[i].reloadSuccess = callback;
                    }
                    
                    loadPopupLayerContent(openedPopups[i], false);
                    break;
                }
            }
        }
        else {
            if (openedPopups.length > 0) {
                $.reloadPopupLayer(openedPopups[openedPopups.length - 1].name);
            }
        }
        
        return this;
    }
    
    function setScreenLockerSize() {
        if (popupLayerScreenLocker) {
            $('#popupLayerScreenLocker').height($(document).height() + "px");
            $('#popupLayerScreenLocker').width($(document.body).outerWidth(true) + "px");
        }
    }
    
    function checkIfItExists(name) {
        if (name) {
            for (var i = 0; i < openedPopups.length; i++) {
                if (openedPopups[i].name == name) {
                    return true;
                }
            }
        }
        return false;
    }
    
    function showScreenLocker(popupObject) {
        if (typeof parent.$ != 'undefined' && parent.$('#header').length == 1) {
            //parent.$('#header').hide();
            //parent.$(document.documentElement).css('overflow', 'hidden');
        }
        if ($("#popupLayerScreenLocker").length) {
            if (openedPopups.length == 1) {
                popupLayerScreenLocker = true;
                setScreenLockerSize();
                //$('#popupLayerScreenLocker').fadeIn(-1);
                $('#popupLayerScreenLocker').show();
            }
            
            if ($.browser.msie && $.browser.version < 7) {
                $("select:not(.hidden-by-jmp)").addClass("hidden-by-jmp hidden-by-" + openedPopups[openedPopups.length - 1].name).css("visibility", "hidden");
            }
            
            $('#popupLayerScreenLocker').css("z-index", parseInt(openedPopups.length == 1 ? 999 : $("#popupLayer_" + openedPopups[openedPopups.length - 2].name).css("z-index")) + 1);
            
        }
        else {
            $("body").append("<div id='popupLayerScreenLocker'><!-- --></div>");
            $("#popupLayerScreenLocker").css({
                position: "absolute",
                background: setupJqueryMPopups.screenLockerBackground,
                left: "0",
                top: "0",
                opacity: setupJqueryMPopups.screenLockerOpacity,
                display: "none"
            });
            showScreenLocker(popupObject);
            
            if (typeof popupObject.enableScreenLockClick != 'undefined' && popupObject.enableScreenLockClick == true) {
                $("#popupLayerScreenLocker").click(function() {
                    $.closePopupLayer();
                });
            }
        }
    }
    
    function hideScreenLocker(popupName) {
        if (openedPopups.length == 0) {
            screenlocker = false;
            $('#popupLayerScreenLocker').fadeOut(-1);
        }
        else {
            $('#popupLayerScreenLocker').css("z-index", parseInt($("#popupLayer_" + openedPopups[openedPopups.length - 1].name).css("z-index")) - 1);
        }
        
        if ($.browser.msie && $.browser.version < 7) {
            $("select.hidden-by-" + popupName).removeClass("hidden-by-jmp hidden-by-" + popupName).css("visibility", "visible");
        }
        if ($.browser.mozilla) {
            //$(document.body).removeAttr('style');
        }
        if (openedPopups.length == 0) {
            if (typeof parent.$ != 'undefined' && parent.$('#header').length == 1) {
                //parent.$('#header').show();
            }
        }
    }
    
    $.setPopupLayersPosition = function(popupElement, animate) {
        if (popupElement) {
            var leftPosition = 0;
            var topPosition = 0;
            if (popupElement.width() < $(window).width()) {
                if ($('#photo', popupElement).length != 0) {
                    leftPosition = (document.documentElement.offsetWidth - 640) / 2;
                }
                else {
                    leftPosition = (document.documentElement.offsetWidth - $('#popWin', popupElement).width()) / 2;
                }
            }
            else {
                leftPosition = document.documentElement.scrollLeft + 5;
            }
            var clientHeight = parent.document.body.clientHeight;
            if (popupElement.height() < clientHeight) {
                if ($('#photo', popupElement).length != 0) {
                    if (parent.document.documentElement.scrollTop > 107) {
                        topPosition = parent.document.documentElement.scrollTop - 107 + (clientHeight - 580) / 2;
                    }
                    else {
                        topPosition = parent.document.documentElement.scrollTop + (clientHeight - 580) / 2;
                    }
                }
                else if (popupElement.attr('id') == 'popupLayer_imagePop') {
                    topPosition = parent.document.documentElement.scrollTop - 107 + (clientHeight - $('#popWin', popupElement).height()) / 2;
                }
                else {
                    topPosition = parent.document.documentElement.scrollTop + (clientHeight - $('#popWin', popupElement).height()) / 2;
                }
            }
            else {
                topPosition = document.documentElement.scrollTop + 5;
            }
            var positions = {
                left: leftPosition + "px",
                top: topPosition + "px"
            };
            
            if (!animate) {
                popupElement.css(positions);
            }
            else {
                popupElement.animate(positions, "slow");
            }
            
            setScreenLockerSize();
        }
        else {
            for (var i = 0; i < openedPopups.length; i++) {
                $.setPopupLayersPosition($("#popupLayer_" + openedPopups[i].name), true);
            }
        }
    }
    
    function showPopupLayerContent(popupObject, newElement, data) {
        var idElement = "popupLayer_" + popupObject.name;
        
        if (newElement) {
            //    SMT.util.showHeadMenuLocker();
            showScreenLocker(popupObject);
            
            $("body").append("<div id='" + idElement + "'><!-- --></div>");
            
            var zIndex = parseInt(openedPopups.length == 1 ? 1000 : $("#popupLayer_" + openedPopups[openedPopups.length - 2].name).css("z-index")) + 2;
        }
        else {
            var zIndex = $("#" + idElement).css("z-index");
        }
        
        var popupElement = $("#" + idElement);
        
        popupElement.css({
            //visibility: "hidden",
            width: popupObject.width == "auto" ? "" : popupObject.width + "px",
            height: popupObject.height == "auto" ? "" : popupObject.height + "px",
            position: "absolute",
            "z-index": zIndex
        });
        
        var linkAtTop = "<a href='#' class='jmp-link-at-top' style='position:absolute; left:-9999px; top:-1px;'>&nbsp;</a><input class='jmp-link-at-top' style='position:absolute; left:-9999px; top:-1px;' />";
        var linkAtBottom = "<a href='#' class='jmp-link-at-bottom' style='position:absolute; left:-9999px; bottom:-1px;'>&nbsp;</a><input class='jmp-link-at-bottom' style='position:absolute; left:-9999px; top:-1px;' />";
        
        popupElement.html(linkAtTop + data + linkAtBottom);
        
        $.setPopupLayersPosition(popupElement);
        
        //popupElement.css("display", "none");
        //popupElement.css("visibility", "visible");
        
        if (newElement) {
            popupElement.fadeIn(-1);
        }
        else {
            popupElement.show();
        }
        
        $("#" + idElement + " .jmp-link-at-top, " +
        "#" +
        idElement +
        " .jmp-link-at-bottom").focus(function() {
            $(focusableElement[focusableElement.length - 1]).focus();
        });
        
        var jFocusableElements = $("#" + idElement + " a:visible:not(.jmp-link-at-top, .jmp-link-at-bottom), " +
        "#" +
        idElement +
        " *:input:visible:not(.jmp-link-at-top, .jmp-link-at-bottom)");
        
        if (jFocusableElements.length == 0) {
            var linkInsidePopup = "<a href='#' class='jmp-link-inside-popup' style='position:absolute; left:-9999px;'>&nbsp;</a>";
            popupElement.find(".jmp-link-at-top").after(linkInsidePopup);
            focusableElement.push($(popupElement).find(".jmp-link-inside-popup")[0]);
        }
        else {
            jFocusableElements.each(function() {
                if (!$(this).hasClass("jmp-link-at-top") && !$(this).hasClass("jmp-link-at-bottom")) {
                    focusableElement.push(this);
                    return false;
                }
            });
        }
        
        $(focusableElement[focusableElement.length - 1]).focus();
        
        popupObject.success();
        
        if (popupObject.reloadSuccess) {
            popupObject.reloadSuccess();
            popupObject.reloadSuccess = null;
        }
        
        if (popupObject.yesClick) {
            if (popupObject.name == 'sysAlertPop') {
                $('#alertYes').bind('click', function() {
                    if (popupObject.enableAutoClose) {
                        $.closePopupLayer('sysAlertPop');
                    }
                    popupObject.yesClick();
                })
            }
            else if (popupObject.name == 'sysConfirmPop') {
                $('#confirmYes').bind('click', function() {
                    if (popupObject.enableAutoClose) {
                        $.closePopupLayer('sysConfirmPop');
                    }
                    popupObject.yesClick();
                })
            }
        }
        
        if (popupObject.noClick) {
            if (popupObject.name == 'sysConfirmPop') {
                $('#confirmNo').bind('click', function() {
                    if (popupObject.enableAutoClose) {
                        $.closePopupLayer('sysConfirmPop');
                    }
                    popupObject.noClick();
                })
            }
        }
        
        // 弹出层移动
        movePop(idElement);
    }
    
    function loadPopupLayerContent(popupObject, newElement) {
        if (newElement) {
            openedPopups.push(popupObject);
        }
        if (popupObject.target != "") {
            if (typeof popupObject.textInfo != "undefined") {
                var createData = '';
                if (popupObject.name == 'sysAlertPop') {
                    createData = alertHtml.replace(/CLOSETAG/ig, getJmpopupsLocalInfo('close')).replace(/YESTAG/ig, getJmpopupsLocalInfo('confirm'));
                    createData = createData.replace(/TEXTINFO/ig, popupObject.textInfo);
                    createData = createData.replace(/TITLEINFO/ig, popupObject.titleInfo);
                    createData = createData.replace(/STYLEINFO/ig, popupObject.styleInfo);
                }
                else if (popupObject.name == 'sysConfirmPop') {
                    createData = confirmHtml.replace(/CLOSETAG/ig, getJmpopupsLocalInfo('close')).replace(/YESTAG/ig, getJmpopupsLocalInfo('confirm')).replace(/NOTAG/ig, getJmpopupsLocalInfo('cancel'));
                    createData = createData.replace(/TEXTINFO/ig, popupObject.textInfo);
                    createData = createData.replace(/TITLEINFO/ig, popupObject.titleInfo);
                    createData = createData.replace(/STYLEINFO/ig, popupObject.styleInfo);
                }
                showPopupLayerContent(popupObject, newElement, createData);
            }
            else {
                showPopupLayerContent(popupObject, newElement, $("#" + popupObject.target).html());
            }
        }
        else if (popupObject.content != "") {
            showPopupLayerContent(popupObject, newElement, popupObject.content);
        }
        else {
            $.ajax({
                url: popupObject.url,
                data: popupObject.parameters,
                cache: popupObject.cache,
                dataType: "html",
                method: "GET",
                complete: function(xhr, statusText) {
                    if ('success' == statusText) {
                        var successHeader = xhr.getResponseHeader("requestSuccess4Ajax");
                        if (successHeader == '0') {
                            SMT.func(config.exceptionProcess);
                        }
                        else if (successHeader == '2') {
                            SMT.func(config.reLogonProcess);
                        }
                        else if (successHeader == '3') {
                            SMT.func(config.timeOutProcess);
                        }
                        else {
                            var ajaxResult = $.trim(xhr.responseText);
                            showPopupLayerContent(popupObject, newElement, ajaxResult);
                        }
                    }
                },
                error: popupObject.error
            });
        }
    }
    
    $.windowResize(function() {
        setScreenLockerSize();
        //$.setPopupLayersPosition();
    });
    
    function movePop1(popId) {
        $('#' + popId).bind('dragstart', function(event) {
            return $(event.target).is('.popup-header');
        }).bind('drag', function(event) {
            $(this).css({
                top: event.offsetY,
                left: event.offsetX
            });
        });
    }
    
    function movePop(popId) {
    
        var iWidth = document.documentElement.clientWidth;
        var iHeight = document.documentElement.clientHeight;
        var moveX = 0;
        var moveY = 0;
        var moveTop = 0;
        var moveLeft = 0;
        
        var docMouseMoveEvent = document.onmousemove;
        var docMouseUpEvent = document.onmouseup;
        
        var divParent = document.getElementById(popId);
        var title$ = $('#popWin > h2', $(divParent));
        
        if (divParent != null) {
        
            title$.css({
                cursor: 'move'
            });
            
            title$.mousedown(function() {
                var evt = getEvent();
                var moveable = true;
                moveX = evt.clientX;
                moveY = evt.clientY;
                moveTop = parseInt(divParent.style.top);
                moveLeft = parseInt(divParent.style.left);
                if ($.browser.mozilla) {
                    $('div.popup').css({
                        "-moz-user-select": "none"
                    });
                    $(document.body).css({
                        "-moz-user-select": "none"
                    });
                }
                else {
                    document.body.onselectstart = function() {
                        return false;
                    };
                    document.body.onselect = function() {
                        return false;
                    };
                }
                document.onmousemove = function() {
                    if (moveable) {
                        var evt = getEvent();
                        var x = moveLeft + evt.clientX - moveX;
                        var y = moveTop + evt.clientY - moveY;
                        //if ( x + $(divParent).width() < iWidth) {
                        divParent.style.left = x + "px";
                        divParent.style.top = y + "px";
                        //}
                    }
                };
                document.onmouseup = function() {
                    if (moveable) {
                        document.onmousemove = docMouseMoveEvent;
                        document.onmouseup = docMouseUpEvent;
                        moveable = false;
                        //            moveX = 0;
                        //            moveY = 0;
                        //            moveTop = 0;
                        //            moveLeft = 0;
                    }
                    if ($.browser.mozilla) {
	                    $('div.popup').css({
	                        "-moz-user-select": ""
	                    });
	                    $(document.body).css({
	                        "-moz-user-select": ""
	                    });
                    }
                    else {
                        document.body.onselectstart = function() {
                            return true;
                        };
                        document.body.onselect = function() {
                            return true;
                        };
                    }
                };
            });
        }
        
        function getEvent() {
            return window.event || arguments.callee.caller.arguments[0];
        }
    };
    
    function getJmpopupsLocalInfo(code) {
        var locale = 'ZH_CN';
        var currLocale = $('#lanNamOptions li:hidden');
        if (currLocale.length > 0) {
            locale = currLocale.attr('locale');
        }
        return locales[locale][code];
    }
    
    /**
     $(document).keydown(function(e){
     if (e.keyCode == 27) {
     $.closePopupLayer();
     }
     });
     **/
})(jQuery);
